package org.ala.tcp_feign_server.impl;

import org.ala.tcp_feign_common.config.TcpFeignConfigure;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_server.ITcpFeignServer;
import org.ala.tcp_feign_server.context.TcpFeignServerContext;
import org.ala.tcp_feign_server.handler.TcpFeignServerInitializeHandler;
import org.slf4j.Logger;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;


/**
 * 默认的服务端实现
 * 
 * @author 骆毅(ala)
 * @date 2024年4月18日
 */
public class DefaultTcpFeignServer implements ITcpFeignServer {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "server");
	
	
	/**
	 * boss线程组
	 */
	protected EventLoopGroup bossGroup;
	/**
	 * worker线程组
	 */
	protected EventLoopGroup workerGroup;
	/**
	 * 服务器
	 */
	protected ServerBootstrap bootstrap;
	/**
	 * 注channel
	 */
	protected Channel mainChannel;
	
	
	/**
	 * 环境记录
	 */
	protected TcpFeignServerContext context;
	
	
	/**
	 * 初始化
	 */
	protected void init(TcpFeignConfigure configure) {
		//	初始化boss和worker线程组
		bossGroup = new NioEventLoopGroup(configure.getBossCount());
		workerGroup = new NioEventLoopGroup(configure.getWorderCount());
		//	创建服务端启动对象
		bootstrap = new ServerBootstrap();
		//	设置线程组
		bootstrap.group(bossGroup, workerGroup)
				 //		服务端通道实现类
				 .channel(NioServerSocketChannel.class)
				 //		设置等待连接队列的连接个数
				 .option(ChannelOption.SO_BACKLOG, 128)
				 //		保持活动连接状态
				 .childOption(ChannelOption.SO_KEEPALIVE, true)
				 //	追加初始化handler
				 .childHandler(new TcpFeignServerInitializeHandler())
				 ;
	}
	
	
	@Override
	public void start(TcpFeignConfigure configure) {
		if (bootstrap == null) {
			init(configure);
		}
		
		//	开启服务端
		try {
			log.info("[[DefaultTcpFeignServer start] tcp-feign服务端 启动");
			mainChannel = bootstrap.bind(configure.getPort()).sync().channel();
		} catch (InterruptedException e) {
			log.error("[DefaultTcpFeignServer start] 启动服务失败 " + e.getMessage(), e);
		}
	}


	@Override
	public void close() {
		if (mainChannel == null) {
			log.info("[[DefaultTcpFeignServer start] 从未开启，何来关闭");
			return;
		}
		//	关闭主channel
		log.info("[DefaultTcpFeignServer close] 关闭主channel");
		try {
			mainChannel.close().sync();
		} catch (InterruptedException e) {
			log.info("[DefaultTcpFeignServer close] 关闭主channel失败. " + e.getMessage(), e);
		}
		
		//	释放资源
		log.info("[DefaultTcpFeignServer close] 释放资源");
		try {
			workerGroup.shutdownGracefully().sync();
			bossGroup.shutdownGracefully().sync();
		} catch (InterruptedException e) {
			log.info("[DefaultTcpFeignServer close] 释放资源失败. " + e.getMessage(), e);
		}
	}

}
